#include "getUsersCommand.h"

QDomDocument GetUsersCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result;

    if (this->isAuthorized(doc)) {
        QDomNodeList roomNodes = doc.elementsByTagName("room");
        if (roomNodes.count() == 1) {
            QString roomName = roomNodes.at(0).toElement().text().trimmed();
            Room* room = DB::getInstance()->findRoom(roomName);
            if (room == NULL) {
                result = "<getUsers><success>FALSE</success><reason>NO_SUCH_ROOM</reason></getUsers>";
            } else {
                result = "<getUsers><success>TRUE</success>";
                QList<User*> users = room->getUsers();
                for (int i = 0; i < users.size(); i++) {
                    QString rule = "USER";
                    if (room->isModerator(users.at(i))) {
                        rule = "MODERATOR";
                    }
                    if (room->isOwner(users.at(i))) {
                        rule = "OWNER";
                    }
                    result.append("<user><login>")
                       .append(users.at(i)->getLogin())
                       .append("</login><rule>")
                       .append(rule)
                       .append("</rule></user>");
                }
                result.append("</getUsers>");
            }
        } else {
            result = "<getUsers><success>FALSE</success><reason>WRONG_XML</reason></getUsers>";
        }
    } else {
        result = "<getUsers><success>FALSE</success><reason>NOT_AUTHORIZED</reason></getUsers>";
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}

